<?php namespace app\admin\controller;
use app\common\controller\AdminBase; 
use app\common\model\AuthRule;
use houdunwang\arr\Arr;
use think\db;
use think\Controller;
//权限控制器
class Rule extends AdminBase{
	private $db;
	public function _initialize(){
		parent::_initialize();
		$this->db=new AuthRule();
		
	}
	public function index(){
		
	}
	
//******************权限表****************************
	//权限列表
	public function rule_list(){
			$data=Arr::tree(db('auth_rule')->order('id')->select(),'title',$fieldPri = 'id', $fieldPid = 'pid');
//			halt($data);
//			$list=$data->paginate(10);
//			halt($list);
			$this->assign('data',$data);
			return $this->fetch();
		
	
	}
	//添加权限
	public function add_rule(){
		if(request()->isPost()){
			$res=$this->db->addData(input('post.'));
			if($res['valid']){
				$this->success($res['msg']);exit;
			}else{
				$this->error($res['msg']);exit;
			}
		}else{
			
				return $this->fetch();
		}
	
	}
	//添加子权限
	public function add_son_rule(){
	    if(request()->isPost()){
	    	$res=$this->db->addData(input('post.'));
			if($res['valid']){
				$this->success($res['msg'],'rule_list');exit;
			}else{
				$this->error($res['msg']);exit;
			}
	    }else{
	    	$id=input('id');
	    	if($id){
	    			    	
//			halt($id);
              $this->assign('id',$id);
	    	}

	    	return $this->fetch();
	    }
	}
	
	//编辑权限
	public function edit_rule(){
		 if(request()->isPost()){
		 	$res=$this->db->editData(input('post.'));
			if($res['valid']){
				$this->success($res['msg'],'rule_list');exit;
			}else{
				$this->error($res['msg']);exit;
			}
		 }else{
		 	$id=input('id');
//			halt($id);
			$data=db('auth_rule')->where('id',$id)->find();
//			halt($data);
            $this->assign('data',$data);
		  	return $this->fetch();
		 }
		
	}
	//删除权限
	public function delete_rule(){
		$id=input('id');
//		halt($id);
      //找子集
		$ids=$this->getSon(db('auth_rule')->select(),$id);
		if(empty($ids)){
			$num=db('auth_rule')->delete($id);
			//删除成功
			if($num){
				$this->success('权限删除成功!');
			}else{
				$this->error('权限删除失败!');
			}
		}else{
			$this->error('请先删除子权限!');
		}
		return $this->fetch();
	}
	
	//递归寻找子类
	public function getSon($data,$id){
		$arr=[];
		
		if(!is_array($data)){
			return false;
		}
	
		foreach($data as $k=>$v){
//			   
			if($v['pid']==$id){
//				echo $v['id'];
//              把子类的id压入数组
                array_push($arr,$v['id']);
//              $arr[$k]=$v['id'];
//             var_dump($arr);
//             echo '</br>';
				$arr=array_merge($arr,$this->getSon($data,$v['id']));
				
			}
		}
//		//把自己压人
//		 $arr[]=$cid;
//		halt($arr);/
		return $arr;
	}
	//*******************用户组**********************
    /**
     * 用户组列表
     */
    
    public function group_list(){
    	$data=db('auth_group')->order('id ')->select();
//  	halt($data);
    	$this->assign('data',$data);
    	return $this->fetch();
    }
    //添加用户组
    public function add_group(){
    	if(request()->isPost()){
			$res=(new \app\common\model\AuthGroup)->addData(input('post.'));
			if($res['valid']){
				$this->success($res['msg']);exit;
			}else{
				$this->error($res['msg']);exit;
			}
		}else{
			
				return $this->fetch();
		}
    	
    }
    //修改用户组
    public function edit_group(){
  
    	if(request()->isPost()){
    		
    		$res=(new \app\common\model\AuthGroup)->editData(input('post.'));
//  		
			if($res['valid']){
				$this->success($res['msg'],'group_list');exit;
			}else{
				$this->error($res['msg'],'group_list');exit;
			}
    	}else{
    		$id=input('id');
    		$data=db('auth_group')->where('id',$id)->find();
//  		var_dump($data);
             $this->assign('data',$data);
    		return $this->fetch();
    	}
    	
    	
    }
    //删除用户组
    public function delete_group(){
    	$id=input('id');
    	halt($id);
    }
    
    //*****************权限-用户组*****************
    /**
     * 分配权限
     */
    public function rule_group(){
    	if(request()->isPost()){
	    		$data=input('post.');
	    		//把数组转换在字符串
	    		if(!empty($data['rules_id'])){
	    			 $data['rules']=implode(',',$data['rules_id']);
	            
		             unset($data['rules_id']);
			         $num=db('auth_group')
					    ->where('id',$data['id'])
					    ->update($data);
		//  		halt($data);
			           if($num){
			           	  $this->success('权限添加成功！','group_list');
			           }else{
			           	  $this->error('权限添加失败');
		              }
	    		}else{
	    			//清空规则字段的数据
	    			$num=db('auth_group')
					    ->where('id',$data['id'])
					    ->update(['rules' => '']);
	    			 if($num){
			           	  $this->success('权限添加成功！','group_list');
			           }else{
			           	  $this->error('权限添加失败');
		              }
	    		}
	           
    	}else{
		    	$id=input('id');
		    	 // 获取用户组数据
		    	$group_data=db('auth_group')->where('id',$id)->find();
		    	
	//	    	把字符串打散为数组：
		    	$group_data['rules']=explode(',',$group_data['rules']);
//		    	 var_dump($group_data['rules']);
		    	// 获取规则数据
		    	 $rule_data=(new \app\common\model\AuthRule)->getTreeData('level');
	//	  	    var_dump($rule_data);
	             $this->assign('group',$group_data);
	             $this->assign('rule',$rule_data);
	//           
		    	 return $this->fetch();
	    	
//	    	$data=Arr::channelLevel(db('auth_rule')->select(), $pid = 0, $html = "&nbsp;" ,$child='id');
//	    	var_dump($data);
    	}
    	
    	
    }
    
    //****************用户-用户组*******************
    /**
     * 添加成员
     */
    public function check_user(){
    	$group_id=input('param.id');
    	$username=input('param.username');
//  	var_dump($username);
    	//获取当前用户组的名称
    	$group_name=db('auth_group')->where('id',$group_id)->value('title');
//  	根据group_id获取全部用户id的****数组*****
         $uids=db('auth_group_access')->where('group_id',$group_id)->column('uid');
//       var_dump($uids);
    	// 判断用户名是否为空
        if(empty($username)){
            $user_data='';
        }else{
        	//用户名是否存在
            $user_data=db('users')->where('username',$username)->select();
        }
//      var_dump($user_data);
        $assign=array(
            'group_name'=>$group_name,
            'group_id'  =>$group_id,
            'uids'      =>$uids,
            'user_data' =>$user_data,
            );
        $this->assign($assign);
        return $this->fetch();
    }
    /**
     * 添加用户到用户组
     */
    public function add_user_to_group(){
    	//users表里的id
    	$data=input('param.');
//  	halt($data);
    	$map=array(
            'uid'=>$data['uid'],
            'group_id'=>$data['group_id']
            );
        $count=db('auth_group_access')->where($map)->count();
//      halt($count);
        if($count==0){
        	//添加新数据
        	$access = new \app\common\model\AuthGroupAccess();
            $access->allowField(true)->save($data);
        }
        $this->success('操作成功','Admin/Rule/check_user',array('id'=>$data['group_id'],'username'=>$data['username']));
    }
    
    /**
     * 管理员列表
     */
   public function admin_user_list(){
	   	$data=(new \app\common\model\AuthGroupAccess())->getAllData();
	   
//		     var_dump($data);
		foreach($data as $k=>$v){
////		
			foreach($v['title'] as $key=>$value){
				$data[$k]['titles'][]=$value['title'];
//				$data[$k]['titles']
			}
//        
		}
//	    var_dump($data);
	      $this->assign('data',$data);
//	      halt($data);
	   	  return $this->fetch();
   }
     /**
     * 添加管理员
     */
    public function add_admin(){
    	if(request()->isPost()){
    		$data=input('post.');
    	   
    		$res=(new \app\common\model\Users())->addData($data);
    	        
			if($res['valid']){
			
				if(!empty($data['group_id'])){
					foreach($data['group_id'] as $k=>$v){
						$new_data=[
						   'uid'=>$res['id'],
						   'group_id'=>$v
						];
						db('auth_group_access')->insert($new_data);
					}
				}
				//操作成功
				$this->success($res['msg'],'admin_user_list');exit;
				
			}else{
				$this->error($res['msg']);exit;
			}
    	}else{
        		
			$auth_group=db('auth_group')->select();
//			halt($auth_group);
			$this->assign('data',$auth_group);
			return $this->fetch();
			
    	}
    }
    /*
     * 编辑管理员
     */
    public function edit_admin(){
    	if(request()->isPost()){
    		$data=input('post.');
    	 
    		$res=(new \app\common\model\Users())->editData($data);
    	        
			if($res['valid']){
//			var_dump($data);
               Db::table('t_auth_group_access')->where('uid',$res['id'])->delete();
				if(!empty($data['group_id'])){
					
					foreach($data['group_id'] as $k=>$v){
						$new_data=[
						   'uid'=>$res['id'],
						   'group_id'=>$v
						];
						db('auth_group_access')->insert($new_data);
					}
					
				}
				//操作成功
				$this->success($res['msg'],'admin_user_list');exit;
				
			}else{
				$this->error($res['msg']);exit;
			}
    	}else{
    		$uid=input('uid');
    		//获取用户组
    		$auth_group=db('auth_group')->select();
    		
    		$this->assign('auth_group',$auth_group);
    		//返回数组
    		$group_id=db('auth_group_access')->where('uid',$uid)->column('group_id');
//  		halt($group_id);
            $this->assign('group_id',$group_id);
    		//获取当前的管理员数据
    		$onedata=db('users')->where('id',$uid)->select();
//  		var_dump($onedata[0]);
    		$this->assign('onedata',$onedata[0]);
//		    halt($auth_group);
			
//  		halt()
    		return $this->fetch();
    	}
    	
    	
    }
    //账号的管理
    public function user_status(){
    	$id=input('uid');
    	$status=input('status');
    	$username=db('users')->where('id',$id)->value('username');
//  	var_dump($status);
    	if($status==0){
    		$num=db('users')
                 ->where('id',$id)
                 ->setField('status',1);
	           if($num){
	          	
	          	  $this->success("$username".'账号可以登录!','admin_user_list');
	            }
    	}else{
    		
	    	  $num=db('users')
	          ->where('id',$id)
	          ->setField('status',0);
	          if($num){
	              $this->success("$username".'账号已禁止登录!','admin_user_list');
	           }
    	}
//  
    	
    }
}

